package com.financing.wap.util;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Transparency;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**  
* 图片水印  
*/  
public class ImageMarkLogoByIconUtil {   
	
	static Logger logger = Logger.getLogger(ImageMarkLogoByIconUtil.class);

  /**  
   * @param args  
 * @throws IOException 
   */  
  public static void main(String[] args) throws IOException {
//      String srcImgPath = "D:/disk/icon/mark1.jpg";   
//      String iconPath = "http://sfacdn.oss-cn-hangzhou.aliyuncs.com//upload/dstUserCert//20190507/dstUserCert_1557209229426.jpeg";   
//      String targerPath = "D:/disk/icon/img_mark_icon.jpg";   
//      // 给图片添加水印     头像   124,124   是否切圆  
////      ImageMarkLogoByIconUtil.markImageByIcon(iconPath, srcImgPath, targerPath,590,1200,120,120,false);  
//      
////测试环境  名片拼接二维码
//      ImageMarkLogoByIconUtil.markImageByIcon(iconPath, srcImgPath,
//				targerPath, 120, 600, 500, 500,false); 
//      iconPath="http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLdClxWzqLGayyicNlMX2CDGmAg6HBOFwxibETljpz2IGyhje4nY8PmkqIm8H0qgYtwknj34Ou4PjQw/132";
//      // 名片 
//      ImageMarkLogoByIconUtil.markImageByIcon(iconPath, targerPath, targerPath,40,220,120,120,true);   
//      //写字
//      BufferedImage markText = markText(targerPath, "未来未来", "", 180, 270,32,Color.BLACK,Font.BOLD);
//      markText(markText, "13052357696", "", 180,320,26,new Color(60,154,242),Font.PLAIN);
//      markText(markText, "开发", "", 180,380,26,Color.BLACK,Font.PLAIN);
//      markText(markText,"huqiyun@superfa.cn" , "", 180,420,26,Color.BLACK,Font.PLAIN);
//      markText(markText,"正气" , "", 180,460,26,Color.BLACK,Font.PLAIN);
//      markText(markText, "上海浦东新区福山路450号新天国际大厦28楼cd", targerPath, 180,510,26,Color.BLACK,Font.PLAIN);
	 
	  //http://sfacdn.oss-cn-hangzhou.aliyuncs.com/downWechat/qrcode/mark.jpg?x-oss-process=image/watermark,image_L3VwbG9hZC9kc3RVc2VyQ2VydC8vMjAxOTA1MDcvZHN0VXNlckNlcnRfMTU1NzIwOTIyOTQyNi5qcGVn
	  
	  String cipherText = Base64.encodeBase64URLSafeString("/upload/dstUserCert//20190507/dstUserCert_1557209229426.jpeg".getBytes());
	  System.out.println(cipherText);
  }
  
/**  
   * 给图片添加水印、可设置水印图片旋转角度  
   * @param iconPath 水印图片路径  
   * @param srcImgPath 源图片路径  
   * @param targerPath 目标图片路径  
   * @param degree 水印图片旋转角度  
   * width  x值
   * height y值
   * iconwidth icon宽    
   * iconheight icon 高 
   * round是否切圆
   */  
  public static void markImageByIcon(String iconPath, String srcImgPath,   
          String targerPath,int width,int height,int iconWidth,int iconHeight,boolean round){
	  
	 markImageByIcon(iconPath, srcImgPath, targerPath,null,width,height,iconWidth,iconHeight,0d,round);   
  }
  
  /**  
   * 给图片添加水印、可设置水印图片旋转角度  
   * @param iconPath 水印图片路径  
   * @param srcImgPath 源图片路径  
   * @param targerPath 目标图片路径  
   * @param degree 水印图片旋转角度  
   * width  x值
   * height y值
   * suofang icon比例缩放
   *round 是否切圆
   */  
  public static void markImageByIcon(String iconPath, String srcImgPath,   
          String targerPath,int width,int height,double suofang,boolean round){
	 markImageByIcon(iconPath, srcImgPath, targerPath,null,width,height,0,0,suofang,round);    
  }
  

  /**  
   * 给图片添加水印、可设置水印图片旋转角度  
   * @param iconPath 水印图片路径  
   * @param srcImgPath 源图片路径  
   * @param targerPath 目标图片路径  
   * @param degree 水印图片旋转角度  
   * width  x值
   * height y值
   * iconwidth icon宽    
   * iconheight icon 高 
   * suofang icon比例缩放
   * round 是否切圆
   */  
  public static void markImageByIcon(String iconPath, String srcImgPath,   
          String targerPath, Integer degree,int width,int height,int iconWidth,int iconHeight,double suofang,boolean round) {   
	  
	  long currentTimeMillis = System.currentTimeMillis();
	  if(StringUtil.isNullOrEmptyStr(iconPath,srcImgPath,targerPath)){
		  logger.info("水印图片路径  ："+iconPath);  
		  logger.info("源图片路径  ："+srcImgPath);  
		  logger.info("目标图片路径  ："+targerPath);  
		  logger.info("图片未添加Icon印章。。。参数缺失。。。"+(System.currentTimeMillis()-currentTimeMillis));  
		  return ;
	  }
      OutputStream os = null;   
      try {   
          Image srcImg = null;
          if(srcImgPath.contains("http")){
        	  srcImg=ImageIO.read(RequstUtil.doRequestStream(srcImgPath));
          }else{
        	  srcImg = ImageIO.read(new File(srcImgPath));   
          }
          BufferedImage buffImg = new BufferedImage(srcImg.getWidth(null),   
                  srcImg.getHeight(null), BufferedImage.TYPE_INT_RGB);   
          logger.info("读取原图片："+srcImg+"花费"+(System.currentTimeMillis()-currentTimeMillis));
          // 得到画笔对象   
          // Graphics g= buffImg.getGraphics();   
          Graphics2D g = buffImg.createGraphics();   
          logger.info("createGraphics花费"+(System.currentTimeMillis()-currentTimeMillis));
          // 设置对线段的锯齿状边缘处理   
//          g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,   
//                  RenderingHints.VALUE_INTERPOLATION_BILINEAR);   
          g.drawImage(srcImg.getScaledInstance(srcImg.getWidth(null), srcImg   
                  .getHeight(null), Image.SCALE_SMOOTH), 0, 0, null);   
          if (null != degree) {
              // 设置水印旋转   
              g.rotate(Math.toRadians(degree),   
                      (double) buffImg.getWidth() / 2, (double) buffImg   
                              .getHeight() / 2);   
          }   
          // 水印图象的路径 水印一般为gif或者png的，这样可设置透明度   
          ImageIcon imgIcon = null;
          BufferedImage zoomInImage = null;
          logger.info("read zoomimage花费begin："+(System.currentTimeMillis()-currentTimeMillis));  
          if(iconPath.contains("http")){
        	  if(suofang!=0){
        		  
//        		  zoomInImage=zoomOutImage(ImageIO.read(RequstUtil.doRequestStream(iconPath)),suofang);
        		  zoomInImage=zoomOutImage(toBufferedImage(Toolkit.getDefaultToolkit().getImage(new URL(iconPath))),suofang);
        	  }else{
//        		  zoomInImage=zoomOutImage(ImageIO.read(RequstUtil.doRequestStream(iconPath)),iconWidth,iconHeight,round);
        		  zoomInImage=zoomOutImage(toBufferedImage(Toolkit.getDefaultToolkit().getImage(new URL(iconPath))),iconWidth,iconHeight,round);
        	  }
          }else{
        	  if(suofang!=0){
//        		  zoomInImage=zoomOutImage(ImageIO.read(new File(iconPath)),suofang);
        		  zoomInImage=zoomOutImage(toBufferedImage(Toolkit.getDefaultToolkit().getImage(iconPath)),suofang);
        	  }else{
//        		  zoomInImage=zoomOutImage(ImageIO.read(new File(iconPath)),iconWidth,iconHeight,round);
        		  zoomInImage=zoomOutImage(toBufferedImage(Toolkit.getDefaultToolkit().getImage(iconPath)),iconWidth,iconHeight,round);
        		  
        	  }
          }
          logger.info("read zoomimage花费end："+(System.currentTimeMillis()-currentTimeMillis));  
          imgIcon =  new ImageIcon(zoomInImage);  
          logger.info("水印图片："+imgIcon);
          // 得到Image对象。   
          Image img = imgIcon.getImage();   

          float alpha = 1f; // 透明度   
          g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP,   
                  alpha));
          // 表示水印图片的位置   
          g.drawImage(img, width, height, null);   
          logger.info("Icon印章。drawImage花费："+(System.currentTimeMillis()-currentTimeMillis));   
          g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));   

          g.dispose();   
          //oss
          if(targerPath.contains("http")||targerPath.contains("DownWechat")) {
              // 生成图片   
              ByteArrayOutputStream baos=new ByteArrayOutputStream();
              ImageIO.write(buffImg, "JPG", baos);
              AliyunOssUtil.writeFile(new ByteArrayInputStream(baos.toByteArray()),targerPath);
          }else{
        	  os = new FileOutputStream(targerPath);   
        	  // 生成图片   
        	  ImageIO.write(buffImg, "JPG", os);
          }

          logger.info("图片完成添加Icon印章。。。。。。花费："+(System.currentTimeMillis()-currentTimeMillis));   
      } catch (Exception e) {   
    	  logger.error("imageMarklogoByIcon error",e);
      }  
  } 
  
  /** 
   * 对图片进行放大 
   * 
   * @param originalImage 原始图片 
   * @param times 放大倍数 
   * @return 
   */ 
  public static BufferedImage zoomInImage(BufferedImage originalImage, Integer times) 
  { 
      int width = originalImage.getWidth() * times; 
      int height = originalImage.getHeight() * times; 
      BufferedImage newImage = new BufferedImage(width, height, originalImage.getType()); 
      Graphics g = newImage.getGraphics(); 
      g.drawImage(originalImage, 0, 0, width, height, null); 
      g.dispose(); 
      return newImage; 
  } 
  

  /** 
   * 对图片进行缩小 
   * 
   * @param originalImage 原始图片 
   * @param times 缩小倍数 
   * @param round 是否切圆
   * @return 缩小后的Image 
   * 
   */ 
  public static BufferedImage zoomOutImage(BufferedImage originalImage,int width, int height,boolean round) 
  { 
      BufferedImage newImage = new BufferedImage(width, height, originalImage.getType()); 
      Graphics g = newImage.getGraphics(); 
      if(round){
    	  //需要保留的区域 图片是一个圆型
    	  int border=1;
    	  Ellipse2D.Double shape = new Ellipse2D.Double(border, border, width - border * 2, width - border * 2);
    	  newImage = ((Graphics2D) g).getDeviceConfiguration().createCompatibleImage(newImage.getWidth(), newImage.getHeight(),
  				Transparency.TRANSLUCENT);
  		  g = newImage.createGraphics();
    	  ((Graphics2D) g).setComposite(AlphaComposite.Clear);
  		  ((Graphics2D) g).fill(new Rectangle(originalImage.getWidth(), originalImage.getHeight()));
  		  ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.9f));
    	  
    	  g.setClip(shape);
    	  g.drawImage(originalImage, border, border, width - border * 2, width - border * 2,null);
    	  
      }else{
    	  g.drawImage(originalImage, 0, 0, width, height, null); 
      }
      g.dispose(); 
      return newImage; 
  } 
  
  /** 
   * 对图片进行缩小   比例
   * 
   * @param originalImage 原始图片 
   * @param times 缩小倍数 
   * @return 缩小后的Image 
   */ 
  public static BufferedImage zoomOutImage(BufferedImage originalImage,double timeshieght) 
  { 
      int width = (int) (originalImage.getWidth() / timeshieght); 
      int height = (int) (originalImage.getHeight() / timeshieght); 
      BufferedImage newImage = new BufferedImage(width, height, originalImage.getType()); 
      Graphics g = newImage.getGraphics(); 
      g.drawImage(originalImage, 0, 0, width, height, null); 
      g.dispose(); 
      return newImage; 
  } 
  
  /**
	 * 绘制图片 
	 * 
	 * @param srcImgPath  图片地址
	 * @param text1  需要绘制图片文字
	 * @param tartget 目标地址
	 * @param width
	 * @param fontSize 字体大小
	 * @return
	 * @throws IOException
	 */
   public static BufferedImage markText(String srcImgPath,String info,String tartget,int width,int height,int fontSize,Color color,int bold)
 throws IOException {
	    Image srcImg = null;
	    //Toolkit.getDefaultToolkit()  解决有图片浮层问题
		if (srcImgPath.contains("http")) {
			srcImg = Toolkit.getDefaultToolkit().getImage(new URL(srcImgPath));
		} else {
			srcImg =  Toolkit.getDefaultToolkit().getImage(srcImgPath);
		}
		return markText(toBufferedImage(srcImg), info, tartget, width, height,fontSize,color,bold);
	}
 	
	  /**
	 * 绘制图片 
	 * 
	 * @param buffImg  图片流
	 * @param text1  需要绘制图片文字
	 * @param x  x坐标
	 * @param y  y坐标
	 * @param alpha
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage markText(BufferedImage buffImg,String info,String targerPath,int x,int y,int fontSize,Color color,int bold)
 throws IOException {
		// 获取层图
		// 创建Graphics2D对象，用在底图对象上绘图
		Graphics2D g2d = buffImg.createGraphics();
		//绘制文案
		g2d.setColor(color);
		Font font = new Font("Microsoft YaHei", bold, fontSize);
		g2d.setFont(font);
		g2d.drawString(info, x, y);
		g2d.dispose();// 释放图形上下文使用的系统资源
		if(StringUtils.isNotBlank(targerPath)){
			if (targerPath.contains("http")||targerPath.toLowerCase().contains("downwechat")) {
				// 生成图片
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ImageIO.write(buffImg, "JPG", baos);
				AliyunOssUtil.writeFile(
						new ByteArrayInputStream(baos.toByteArray()), targerPath);
			} else{
				FileOutputStream os = new FileOutputStream(targerPath);
				// 生成图片
				ImageIO.write(buffImg, "JPG", os);
			}
		}
		return buffImg;
	}
	public static BufferedImage toBufferedImage(Image image) {
	    if (image instanceof BufferedImage) {
	        return (BufferedImage) image;
	    }
	    // This code ensures that all the pixels in the image are loaded  
	    image = new ImageIcon(image).getImage();
	    BufferedImage bimage = null;
	    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
	    try {
	        int transparency = Transparency.OPAQUE;
	        GraphicsDevice gs = ge.getDefaultScreenDevice();
	        GraphicsConfiguration gc = gs.getDefaultConfiguration();
	        bimage = gc.createCompatibleImage(image.getWidth(null), image.getHeight(null), transparency);
	    } catch (HeadlessException e) {
	        // The system does not have a screen  
	    }
	    if (bimage == null) {
	        // Create a buffered image using the default color model  
	        int type = BufferedImage.TYPE_INT_RGB;
	        bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
	    }
	    // Copy image to buffered image  
	    Graphics g = bimage.createGraphics();
	    // Paint the image onto the buffered image  
	    g.drawImage(image, 0, 0, null);
	    g.dispose();
	    return bimage;
	} 
  
}  